package com.ruoyi.web.controller.kujiale;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.JYXResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.DesignStatisticsQueryVO;
import com.ruoyi.system.domain.vo.DesignStatisticsVO;
import com.ruoyi.system.dto.ProjectDTO;
import com.ruoyi.system.dto.design.DesignBatchCreateDTO;
import com.ruoyi.system.dto.kujiale.PageResponse;
import com.ruoyi.system.dto.kujiale.info.RenderingImage;
import com.ruoyi.system.dto.kujiale.pano.RoamItem;
import com.ruoyi.system.enums.SpaceTypeEnum;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.PageConvertUtil;
import com.ruoyi.system.utils.SysUserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 批量创建设计信息控制器
 */
@RestController
@RequestMapping("/system/design")
@Api(tags = "批量设计信息管理")
public class DesignBatchController extends BaseController {

    @Autowired
    private DesignBatchService designBatchService;

    @Autowired
    private DesignBaseService designBaseService;

    @Autowired
    private DesignSchemeService designSchemeService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private IOperationLogService operationLogService;

    @Autowired
    private KuJiaLeService kuJiaLeService;

    @Autowired
    private DesignerService designerService;

    /**
     * 批量创建设计基础信息、设计方案及图片
     */
    @PostMapping("/batchCreate")
    @ApiOperation("批量创建设计基础信息、设计方案及图片")
    public JYXResult batchCreate(@Validated @RequestBody DesignBatchCreateDTO batchCreateDTO) {
        Long designBaseId = designBatchService.batchCreate(batchCreateDTO);
        return JYXResult.success("批量创建成功", designBaseId);
    }


    /**
     * 根据设计ID查询完整设计信息（基础设计+方案+图片+操作日志）
     */
    @GetMapping("/detail/{designId}")
    @ApiOperation("查询设计完整详情（含操作日志）")
    public JYXResult getDesignDetailWithLogs(@PathVariable Long designId) {
        // 1. 查询基础设计信息
        DesignBase designBase = designBaseService.getById(designId);
        if (designBase == null) {
            return JYXResult.error("设计信息不存在");
        }

        ProjectDTO project = projectService.getProjectById(designBase.getProjectId());

        if (project == null) {
            return JYXResult.error("项目信息不存在");
        }

        // 2. 查询该设计下的所有方案
        List<DesignScheme> schemes = designSchemeService.selectByDesignBaseId(designId);

        // 6. 查询该设计的操作日志
        List<OperationLog> operationLogs = operationLogService.getLogsByBusinessId(
                designId.toString()
        );

        // 7. 封装完整结果
        Map<String, Object> result = new HashMap<>(3);
        result.put("designBase", designBase);
        result.put("schemes", schemes);
        result.put("operationLogs", operationLogs);
        result.put("customerId", project.getH5UserId());

        return JYXResult.success(result);
    }

    /**
     * 根据设计ID查询完整设计信息For案例作品 H5
     */
    @GetMapping("/detail/case/h5/{designId}")
    @ApiOperation("根据设计ID查询完整设计信息For案例作品 H5")
    public JYXResult getDesignDetailCaseForH5(@PathVariable Long designId) {
        // 1. 查询基础设计信息
        DesignBase designBase = designBaseService.getById(designId);
        if (designBase == null) {
            return JYXResult.error("设计信息不存在");
        }

        ProjectDTO project = projectService.getProjectByIdNoValidatePermission(designBase.getProjectId());

        if (project == null) {
            return JYXResult.error("项目信息不存在");
        }

        Long designerId = designBase.getDesignerId();
        DesignerGen designerGen = designerService
                .lambdaQuery()
                .eq(DesignerGen::getUserId, designerId)
                .one();


// 7. 封装完整结果
        Map<String, Object> result = new HashMap<>(3);
        // 2. 查询该设计下的所有方案
        List<DesignScheme> schemes = designSchemeService.selectByDesignBaseId(designId);
        if (CollectionUtil.isNotEmpty(schemes)) {
            Optional<DesignScheme> first = schemes.stream().filter(x -> x.getIsAdopted() != null && x.getIsAdopted().equals(1)).findFirst();
            if (first.isPresent()) {
                DesignScheme designScheme = first.get();
                schemes = Lists.newArrayList(designScheme);
                if (designScheme.getUseOnlineDesign() != null && designScheme.getUseOnlineDesign().equals(1)
                        && StringUtils.isNotBlank(designScheme.getOnlineDesignId())) {
                    List<DesignSchemeImage> kujialeImg = getKujialeImg(designScheme.getOnlineDesignId());
                    designScheme.setImages(kujialeImg);
                    // 查询全屋漫游图
                    // 调用服务层获取漫游列表
                    Long creatorId = designBase.getCreatorId();
                    String kujialeIdBySysUserId = SysUserUtils.getKujialeIdBySysUserId(creatorId);
                    if (StringUtils.isNotBlank(kujialeIdBySysUserId)) {
                        List<RoamItem> roamList = kuJiaLeService.getRoamList(kujialeIdBySysUserId, designScheme.getOnlineDesignId());
                        if (CollectionUtil.isNotEmpty(roamList)) {
                            result.put("roamList", roamList);
                        }
                    }
                }
            }
        }

        result.put("designBase", designBase);
        result.put("schemes", schemes);
        result.put("customerId", project.getH5UserId());
        result.put("designerGen", designerGen);

        return JYXResult.success(result);
    }

    private List<DesignSchemeImage> getKujialeImg(String kujialeDesignId) {
        PageConvertUtil.PageParam convert = PageConvertUtil.convert(1, 50);
        // 明确返回数据类型为 PageResponse，Swagger 可通过 @ApiResponse 关联
        PageResponse<RenderingImage> pageResponse = kuJiaLeService.renderpicList(kujialeDesignId, convert.getStart(), convert.getNum());
        List<RenderingImage> result = pageResponse.getResult();
        if (CollectionUtil.isEmpty(result)) {
            return null;
        }
//        Map<Integer, String> picTypeNameMapeMap = ImmutableMap.of(0, "普通图", 1, "全景图", 3, "俯视图");
        List<DesignSchemeImage> resultList = Lists.newArrayList();

        for (RenderingImage renderingImage : result) {
            DesignSchemeImage designSchemeImage = new DesignSchemeImage();
            resultList.add(designSchemeImage);

            if ( StringUtils.isBlank(renderingImage.getImg())) {
                continue;
            }
            designSchemeImage.setFilePath(renderingImage.getImg());
            SpaceTypeEnum byLabel = SpaceTypeEnum.getByLabel(renderingImage.getRoomName());
            if (byLabel != null) {
                designSchemeImage.setSpaceName(byLabel.getLabel());
                designSchemeImage.setSpaceType(byLabel.getValue());
            } else {
                designSchemeImage.setSpaceName(StringUtils.isBlank(renderingImage.getRoomName()) || renderingImage.getRoomName().equals("未知") ? SpaceTypeEnum.OTHER.getLabel() : renderingImage.getRoomName());
                designSchemeImage.setSpaceType(SpaceTypeEnum.OTHER.getValue());
            }

        }
        return resultList;

    }

    @Autowired
    private IDesignStatisticsService designStatisticsService;

    /**
     * 获取设计项目统计数据
     */
    @GetMapping("/statistics")
    @ApiOperation(value = "获取设计项目统计数据", notes = "返回设计项目的各类统计指标，支持多条件筛选")
    public JYXResult getDesignStatistics(DesignStatisticsQueryVO query) {
        DesignStatisticsVO statistics = designStatisticsService.getDesignStatistics(query);
        return JYXResult.success(statistics);
    }
}